/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.hauntedhousesweb.web;

import cz.muni.fi.hauntedhouses.service.HouseService;
import cz.muni.fi.hauntedhouses.to.HouseTO;
import java.util.List;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;

/**
 *
 * @author Jan Volmut, 324836
 */
@UrlBinding("/houses/{$event}/{house.id}")
public class HousesActionBean implements ActionBean {

    private ActionBeanContext context;
    
    @SpringBean
    private HouseService houseService;
    
    @ValidateNestedProperties(value = {
    @Validate(on = {"add", "save"}, field = "name", required = true)          
    })
    private HouseTO house;
    
    @DefaultHandler
    public Resolution all() {
        if (houseService == null) {
            return new ForwardResolution("/jetozle.jsp"); //preda rizeni
        }
        return new ForwardResolution("/showHouses.jsp"); //preda rizeni
    }
    
    public List<HouseTO> getHouses() {
        return houseService.findAll();
    }
    
    public Resolution add() {
        houseService.create(house);
        return new RedirectResolution(this.getClass(), "all");
    }
    
    public Resolution delete() {
        houseService.delete(house);
        return new RedirectResolution(this.getClass(), "all");
    }

    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "save"})
    public void loadHousesFromDatabase() {
        String ids = context.getRequest().getParameter("house.id");
        if (ids == null) return;
        house = houseService.get(Long.parseLong(ids));
    }
 
    public Resolution edit() {
        return new ForwardResolution("/editHouses.jsp");
    }
 
    public Resolution save() {
        houseService.update(house);
        return new RedirectResolution(this.getClass(), "all");
    }
    
    public HouseTO getHouse() {
        return house;
    }

    public void setHouse(HouseTO house) {
        this.house = house;
    }
 
    
    @Override
    public ActionBeanContext getContext() {
        return this.context;
    }

    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }
    
}
